package org.rosildos.ricotta;


import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.junit.Assert;
import org.junit.Test;
import org.rosildos.ricotta.model.User;

public class HibernateUserFinder extends AbstractHibernateTestCase {

	private static final String USER_BY_EMAIL_OR_USERNAME_HQL = "from User where userName = ? or email = ?";
	private static final String USER_BY_IGNORED_CASE_EMAIL_OR_USERNAME_HQL = "from User where upper(userName) = upper(?) or upper(email) = upper(?)";
	private static Logger logger = Logger.getLogger(HibernateUserFinder.class);
	
	@Test
	public void testUserFinderByUserNameOrEmail_existingByUserName() {
		final String userName = "foo01";
		final User user   = findUser(userName);
		logger.info("Found user with item [" + userName + "]| " + user);
		Assert.assertNotNull(user);
		Assert.assertEquals(userName, user.getUsername());		
	}

	@Test
	public void testUserFinderByUserNameOrEmail_existingByEmail() {
		final String email = "foo01@foo.com";
		final User user   = findUser(email);
		logger.info("Found user with item [" + email + "]| " + user);
		Assert.assertNotNull(user);
		Assert.assertEquals(email, user.getEmail());		
	}
	

	@Test
	public void testUserFinderByUserNameOrEmail_null() {
		final String email = null;
		final User user   = findUser(email);
		logger.info("Found user with item [" + email + "]| " + user);
		Assert.assertNull(user);
	}

	
	
	@Test
	public void testUserFinderByUserNameOrEmail_ignoring_case() {
		final String email = "FOO01@foo.cOM";
		final User user   = findUser(email);
		logger.info("Found user with item [" + email + "]| " + user);
		Assert.assertNotNull(user);
		Assert.assertTrue("different emails", StringUtils.equalsIgnoreCase(email, user.getEmail()));	
	}	
	
	
	@Test
	public void testUserFinderByUserNameOrEmail_NonExisting() {
		final String userName = "NON_EXISTING_USER";		
		final User user   = findUser(userName);
		logger.info("Found user with item [" + userName + "]| " + user);
		Assert.assertNull(user);
	}

	
	
	private User findUser(final String item) {
		final Query query = session.createQuery(USER_BY_IGNORED_CASE_EMAIL_OR_USERNAME_HQL);
		query.setString(0, item);
		query.setString(1, item);
		final User user   = (User) query.uniqueResult();
		return user;
	}
	

	@Test
	public void testEquality() {
		final String userName = "foo01";		
		final User user1   = findUser(userName);
		final User user2   = findUser(userName);
		Assert.assertNotNull(user1);
		Assert.assertNotNull(user2);
		Assert.assertEquals(user1, user2);
		
	}
	
}
